const ACCESS_KEY = "pqPdxFGcQ0UMWMjEUB7XgGrn";
const ACCESS_SECRET = "Bps8plabnGxhdWsScMnzPLh5jZdBKM7G";
export function getToken() {
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync("baidu-token");
		if (!token) {
			uni.request({
				url: `https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ACCESS_KEY}&client_secret=${ACCESS_SECRET}`,
				method: "POST",
				success: (res) => {
					console.log("getToken-res", res.data.access_token);
					uni.setStorageSync("baidu-token", res.data.access_token);
				}
			});
		}
	});
}

export async  function soundReco(data,dev_pid) { //语音识别
console.log("data",data);
	let token = uni.getStorageSync("baidu-token");
	if (!token) {
		console.log("reget token");
		await getToken();
	}
	console.log("baidu-token:",token)
	return new Promise((resolve, regest) => {
		//dev_pid 普通话=1537 ;1637=粤语  1837=四川话
		uni.request({
			url: `https://vop.baidu.com/server_api?dev_pid=1537&cuid=198656miniapp&token=${token}`,
			method: "POST",
			data: data,
			header: {
				"Content-Type": "audio/pcm;rate=16000"
			},
			success: (res) => {
				console.log(res)
				if(res.err_msg === "success."){
					resolve(res.data.result[0]);
				}else{
					
				}
			},
			fail: regest
		})
	});
}

export function imageReco(data) { //图像识别
	let token = uni.getStorageSync("user-token");
	if (!token) {
		console.log("reget token");
		getToken();
	}
	return new Promise((resolve, regest) => {
		uni.request({
			url: `https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient?access_token=${token}`,
			method: "POST",
			data: data,
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			success: (res) => {
				console.log(res)
				resolve(res.data.result[0].name);
			},
			fail: regest
		})
	});
}
